<?php

namespace Home\Service;

use Home\Common\FIdConst;

/**
 * 店铺Service
 *
 * @author 李静波
 */
class ShopService extends PSIBaseService {

	private function shopTypeToLabel($shopType) {
		if ($shopType == 0) {
			return "实体店";
		} else if ($shopType == 1) {
			return "淘宝店";
		} else if ($shopType == - 1) {
			return "其他";
		} else {
			return "";
		}
	}

	public function shopList() {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$result = array();
		
		$db = M();
		
		$sql = "select id, code, name, address, shop_master_id, shop_type,
					use_pos, warehouse_id
				from t_shop
				order by code";
		$data = $db->query($sql);
		foreach ( $data as $v ) {
			$item = array(
					"id" => $v["id"],
					"code" => $v["code"],
					"name" => $v["name"],
					"address" => $v["address"],
					"shopType" => $this->shopTypeToLabel($v["shop_type"]),
					"usePOS" => $v["use_pos"] == 1 ? "启用" : ""
			);
			
			$masterId = $v["shop_master_id"];
			$warehouseId = $v["warehouse_id"];
			
			if ($masterId) {
				$sql = "select name from t_user where id = '%s' ";
				$d = $db->query($sql, $masterId);
				if ($d) {
					$item["masterName"] = $d[0]["name"];
				}
			}
			
			if ($warehouseId) {
				$sql = "select name from t_warehouse where id = '%s' ";
				$d = $db->query($sql, $warehouseId);
				if ($d) {
					$item["warehouseName"] = $d[0]["name"];
				}
			}
			
			$result[] = $item;
		}
		
		return $result;
	}

	public function editShop($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$id = $params["id"];
		$code = $params["code"];
		$name = $params["name"];
		$address = $params["address"];
		$masterId = $params["masterId"];
		$shopType = $params["shopType"];
		$usePOS = $params["usePOS"];
		$warehouseId = $params["warehouseId"];
		
		$db = M();
		$db->startTrans();
		
		$us = new UserService();
		
		if (! $us->userExists($masterId, $db)) {
			$db->rollback();
			return $this->bad("没有选择店长");
		}
		
		$ws = new WarehouseService();
		if (! $ws->warehouseExists($warehouseId, $db)) {
			$db->rollback();
			return $this->bad("没有选择出库仓库");
		}
		
		$dataOrg = $us->getLoginUserDataOrg();
		$companyId = $us->getCompanyId();
		
		$log = null;
		
		if ($id) {
			// 编辑
			
			// 检查编码是否已经存在
			$sql = "select count(*) as cnt from t_shop 
					where code = '%s' and id <> '%s' ";
			$data = $db->query($sql, $code, $id);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("编码[$code]已经存在");
			}
			
			$sql = "update t_shop
					set code = '%s', name = '%s', address = '%s',
						shop_master_id = '%s', shop_type = %d,
						use_pos = %d, warehouse_id = '%s'
					where id = '%s' ";
			$rc = $db->execute($sql, $code, $name, $address, $masterId, $shopType, $usePOS, 
					$warehouseId, $id);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "编辑店铺[编码 = {$code} 名称 = {$name}]";
		} else {
			// 新建
			
			// 检查编码是否已经存在
			$sql = "select count(*) as cnt from t_shop where code = '%s' ";
			$data = $db->query($sql, $code);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("编码[$code]已经存在");
			}
			
			$idGen = new IdGenService();
			$id = $idGen->newId($db);
			
			$sql = "insert into t_shop(id, code, name, address, shop_master_id, shop_type, use_pos,
						warehouse_id, data_org, company_id)
					values ('%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s')";
			$rc = $db->execute($sql, $id, $code, $name, $address, $masterId, $shopType, $usePOS, 
					$warehouseId, $dataOrg, $companyId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "新增店铺[编码 = {$code} 名称 = {$name}]";
		}
		
		if ($log) {
			$bs = new BizlogService();
			$bs->insertBizlog($log, "店铺管理");
		}
		
		$db->commit();
		
		return $this->ok($id);
	}

	public function shopInfo($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$result = array();
		
		$id = $params["id"];
		
		$db = M();
		
		$sql = "select code, name, address, shop_master_id,
					shop_type, use_pos, warehouse_id
				from t_shop
				where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			return $result;
		}
		$result["code"] = $data[0]["code"];
		$result["name"] = $data[0]["name"];
		$result["address"] = $data[0]["address"];
		$result["shopType"] = $data[0]["shop_type"];
		$result["usePOS"] = $data[0]["use_pos"] == 1;
		$masterId = $data[0]["shop_master_id"];
		$warehouseId = $data[0]["warehouse_id"];
		
		if ($masterId) {
			$sql = "select name from t_user where id = '%s' ";
			$data = $db->query($sql, $masterId);
			if ($data) {
				$result["masterId"] = $masterId;
				$result["masterName"] = $data[0]["name"];
			}
		}
		
		if ($warehouseId) {
			$sql = "select name from t_warehouse where id = '%s' ";
			$data = $db->query($sql, $warehouseId);
			if ($data) {
				$result["warehouseId"] = $warehouseId;
				$result["warehouseName"] = $data[0]["name"];
			}
		}
		
		return $result;
	}

	public function deleteShop($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$id = $params["id"];
		
		$db = M();
		$db->startTrans();
		
		$sql = "select code, name from t_shop where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("要删除的店铺不存在");
		}
		$code = $data[0]["code"];
		$name = $data[0]["name"];
		
		$sql = "select count(*) as cnt 
				from t_pos_bill 
				where shop_id = '%s' ";
		$data = $db->query($sql, $id);
		$cnt = $data[0]["cnt"];
		if ($cnt > 0) {
			$db->rollback();
			return $this->bad("店铺已经在收银单中使用了，不能再删除");
		}
		
		$sql = "delete from t_shop_user where shop_id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$sql = "delete from t_shop where id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$log = "删除店铺[编码 = {$code}, 名称 = {$name}]";
		$bs = new BizlogService();
		$bs->insertBizlog($log, "店铺管理");
		
		$db->commit();
		
		return $this->ok();
	}

	public function selectUsers($idList) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$list = explode(",", $idList);
		if (! $list) {
			return array();
		}
		
		$result = array();
		
		$sql = "select u.id, u.name, u.login_name, o.full_name
				from t_user u, t_org o
				where u.org_id = o.id ";
		$queryParams = array();
		$ds = new DataOrgService();
		$rs = $ds->buildSQL(FIdConst::PERMISSION_MANAGEMENT, "u");
		if ($rs) {
			$sql .= " and " . $rs[0];
			$queryParams = $rs[1];
		}
		
		$sql .= " order by convert(u.name USING gbk) collate gbk_chinese_ci";
		$data = M()->query($sql, $queryParams);
		
		$index = 0;
		
		foreach ( $data as $v ) {
			if (! in_array($v["id"], $list)) {
				$result[$index]["id"] = $v["id"];
				$result[$index]["name"] = $v["name"];
				$result[$index]["loginName"] = $v["login_name"];
				$result[$index]["orgFullName"] = $v["full_name"];
				
				$index ++;
			}
		}
		
		return $result;
	}

	public function editShopUser($params) {
		if ($this->isNotOnline()) {
			return $this->notOnlineError();
		}
		
		$id = $params["id"];
		$userIdList = $params["userIdList"];
		
		$db = M();
		$db->startTrans();
		
		$sql = "select code, name from t_shop where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("没有选择店铺");
		}
		$code = $data[0]["code"];
		$name = $data[0]["name"];
		
		$uidArray = explode(",", $userIdList);
		
		$sql = "delete from t_shop_user where shop_id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$idGen = new IdGenService();
		$us = new UserService();
		foreach ( $uidArray as $userId ) {
			if (! $us->userExists($userId, $db)) {
				$db->rollback();
				return $this->bad("选择的用户不存在");
			}
			
			$sql = "insert into t_shop_user (id, shop_id, user_id, auto_goto_pos)
					values ('%s', '%s', '%s', 1)";
			$rc = $db->execute($sql, $idGen->newId($db), $id, $userId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		$log = "为店铺[编码 = {$code}, 名称 = {$name}]设置店员";
		$bs = new BizlogService();
		$bs->insertBizlog($log, "店铺管理");
		
		$db->commit();
		
		return $this->ok($id);
	}

	public function userList($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$id = $params["id"];
		
		$db = M();
		$result = array();
		$sql = "select u.org_code, u.login_name, u.name, o.full_name
				from t_shop_user s, t_user u, t_org o
				where s.shop_id = '%s' and s.user_id = u.id and u.org_id = o.id
				order by u.org_code";
		$data = $db->query($sql, $id);
		foreach ( $data as $v ) {
			$item = array(
					"code" => $v["org_code"],
					"loginName" => $v["login_name"],
					"name" => $v["name"],
					"orgName" => $v["full_name"]
			);
			
			$result[] = $item;
		}
		
		return $result;
	}

	public function userListForEdit($params) {
		if ($this->isNotOnline()) {
			return $this->emptyResult();
		}
		
		$id = $params["id"];
		
		$db = M();
		$result = array();
		$sql = "select u.org_code, u.login_name, u.name, o.full_name, u.id
				from t_shop_user s, t_user u, t_org o
				where s.shop_id = '%s' and s.user_id = u.id and u.org_id = o.id
				order by u.org_code";
		$data = $db->query($sql, $id);
		foreach ( $data as $v ) {
			$item = array(
					"id" => $v["id"],
					"code" => $v["org_code"],
					"loginName" => $v["login_name"],
					"name" => $v["name"],
					"orgName" => $v["full_name"]
			);
			
			$result[] = $item;
		}
		
		return $result;
	}
}